from flask import Blueprint, request, jsonify
from app.services.product_service import ProductService
from app.utils.response_handler import success_response, error_response
# from app.utils.validation import validate_product_data

product_bp = Blueprint('product_bp', __name__)


@product_bp.route('', methods=['POST'])
def create_product():
    """创建产品"""
    data = request.json

    # errors = validate_product_data(data)
    # if errors:
    #     return error_response(errors, 400)

    try:
        new_product = ProductService.create_product(data)
        return success_response(new_product.to_dict(), 201)
    except Exception as e:
        return error_response(str(e), 500)


@product_bp.route('', methods=['GET'])
def get_products():
    """获取所有产品"""
    try:
        products = ProductService.get_all_products()
        return success_response([product.to_dict() for product in products])
    except Exception as e:
        return error_response(str(e), 500)


@product_bp.route('/<int:product_id>', methods=['GET'])
def get_product(product_id):
    """获取单个产品"""
    try:
        product = ProductService.get_product_by_id(product_id)
        return success_response(product.to_dict())
    except Exception as e:
        return error_response(str(e), 404)


@product_bp.route('/<int:product_id>', methods=['PUT'])
def update_product(product_id):
    """更新产品信息"""
    data = request.json
    try:
        updated_product = ProductService.update_product(product_id, data)
        return success_response(updated_product.to_dict())
    except Exception as e:
        return error_response(str(e), 400)


@product_bp.route('/<int:product_id>', methods=['DELETE'])
def delete_product(product_id):
    """删除产品"""
    try:
        ProductService.delete_product(product_id)
        return success_response({"message": "Product deleted successfully"})
    except Exception as e:
        return error_response(str(e), 400)